package com.light.netty.client.handler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;

public class UdpBusinessClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private String name;

    public UdpBusinessClientHandler(String name){
        this.name = name;
    }

    /**
     * 当Channel已经打开并且连接到对端时调用
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String message = name + "UDP Client: Hello Server";

        // 注意：一定要是通过channel().writeAndFlush(packet)才能发送到服务端
        for (int i = 0; i < 500; i++) {
            int finalI = i;
            ByteBuf buffer = Unpooled.copiedBuffer((message+finalI).getBytes(CharsetUtil.UTF_8));
            // 构造数据报，指定服务器地址和端口
            DatagramPacket packet = new DatagramPacket(
                    buffer,
                    new InetSocketAddress("localhost", 8082) // 服务器IP和端口
            );
            // 注意：一定要是通过channel().writeAndFlush(packet)才能发送到服务端
            ctx.channel().writeAndFlush(packet).addListener(future -> {
                if (future.isSuccess()) {
                    System.out.println(name+"UDP Client Message sent successfully");
                } else {
                    System.err.println(name+"UDP Client Failed to send message: " + future.cause());
                }
            });
        }
    }


    /**
     * 直接发送文本消息
     * @param ctx
     * @param packet
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) throws Exception {
        // 获取接收到的消息内容（字符串）
        String msg = packet.content().toString(CharsetUtil.UTF_8);
        System.out.println(name+"服务端确认消息: " + msg);
    }
}